﻿using DT.GoogleAnalytics.Metro;
using FantasyWereld.Common;
using FantasyWereld.Data;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Windows.ApplicationModel.Search;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

// The Search Contract item template is documented at http://go.microsoft.com/fwlink/?LinkId=234240

namespace FantasyWereld.Views
{
    /// <summary>
    /// This page displays search results when a global search is directed to this application.
    /// </summary>
    public sealed partial class SearchResultsPage : FantasyWereld.Common.LayoutAwarePage
    {
        // Collection of MediaObjectDataItem collections representing search results
        private Dictionary<string, List<FWDataItem>> _results = new Dictionary<string, List<FWDataItem>>();

        public SearchResultsPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            var queryText = navigationParameter as String;

            // TODO: Application-specific searching logic.  The search process is responsible for
            //       creating a list of user-selectable result categories:
            //
            //       filterList.Add(new Filter("<filter name>", <result count>));
            //
            //       Only the first filter, typically "All", should pass true as a third argument in
            //       order to start in an active state.  Results for the active filter are provided
            //       in Filter_SelectionChanged below.

            var filterList = new List<Filter>();
            filterList.Add(new Filter("Alle", 0, true));

            var groups = FWDataSource.GetGroups("AllGroups");
            string query = queryText.ToLower();
            var all = new List<FWDataItem>();
            _results.Add(("Alle"), all);

            foreach (var group in groups)
            {
                var items = new List<FWDataItem>();

                if (!_results.ContainsKey(group.Title))
                {
                    _results.Add(group.Title, items);
                }

                foreach (var item in group.Items)
                {
                    if ((!String.IsNullOrEmpty(item.Age) && item.Age.ToLower().Contains(query)) ||
                        (!String.IsNullOrEmpty(item.Author) && item.Author.ToLower().Contains(query)) ||
                        (!String.IsNullOrEmpty(item.Content) && item.Content.ToLower().Contains(query)) ||
                        (!String.IsNullOrEmpty(item.Description) && item.Description.ToLower().Contains(query)) ||
                        (!String.IsNullOrEmpty(item.Edition) && item.Edition.ToLower().Contains(query)) ||
                        (!String.IsNullOrEmpty(item.ISBN) && item.ISBN.ToLower().Contains(query)) ||
                        (!String.IsNullOrEmpty(item.Reviewer) && item.Reviewer.ToLower().Contains(query)) ||
                        (!String.IsNullOrEmpty(item.SubGenre) && item.Publisher.ToLower().Contains(query)) ||
                        (!String.IsNullOrEmpty(item.Publisher) && item.Publisher.ToLower().Contains(query)) ||
                        (!String.IsNullOrEmpty(item.PublishDate) && item.PublishDate.ToLower().Contains(query)) ||
                        (!String.IsNullOrEmpty(item.Quote) && item.Quote.ToLower().Contains(query)) ||
                        (!String.IsNullOrEmpty(item.Reviewer) && item.Reviewer.ToLower().Contains(query)) ||
                        (!String.IsNullOrEmpty(item.SubGenre) && item.SubGenre.ToLower().Contains(query)) ||
                        (!String.IsNullOrEmpty(item.Title) && item.Title.ToLower().Contains(query)) ||
                        (!String.IsNullOrEmpty(item.TitleOriginal) && item.Title.ToLower().Contains(query)) ||
                        (!String.IsNullOrEmpty(item.Translator) && item.Translator.ToLower().Contains(query)))
                    {
                        all.Add(item);
                        items.Add(item);
                    }
                }

                // Only add group when count larger than 0
                if (items.Count > 0)
                    filterList.Add(new Filter(group.Title, items.Count, false));
            }

            filterList[0].Count = all.Count;

            // Communicate results through the view model
            this.DefaultViewModel["QueryText"] = '\u201c' + queryText + '\u201d';
            this.DefaultViewModel["Filters"] = filterList;
            this.DefaultViewModel["ShowFilters"] = filterList.Count > 1;
        }

        /// <summary>
        /// Invoked when a filter is selected using the ComboBox in snapped view state.
        /// </summary>
        /// <param name="sender">The ComboBox instance.</param>
        /// <param name="e">Event data describing how the selected filter was changed.</param>
        void Filter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Determine what filter was selected
            var selectedFilter = e.AddedItems.FirstOrDefault() as Filter;
            if (selectedFilter != null)
            {
                // Mirror the results into the corresponding Filter object to allow the
                // RadioButton representation used when not snapped to reflect the change
                selectedFilter.Active = true;

                // TODO: Respond to the change in active filter by setting this.DefaultViewModel["Results"]
                //       to a collection of items with bindable Image, Title, Subtitle, and Description properties
                this.DefaultViewModel["Results"] = _results[selectedFilter.Name]; 

                // Ensure results are found
                object results;
                ICollection resultsCollection;
                if (this.DefaultViewModel.TryGetValue("Results", out results) &&
                    (resultsCollection = results as ICollection) != null &&
                    resultsCollection.Count != 0)
                {
                    VisualStateManager.GoToState(this, "ResultsFound", true);
                    return;
                }
            }

            // Display informational text when there are no search results.
            VisualStateManager.GoToState(this, "NoResultsFound", true);
        }

        /// <summary>
        /// Invoked when a filter is selected using a RadioButton when not snapped.
        /// </summary>
        /// <param name="sender">The selected RadioButton instance.</param>
        /// <param name="e">Event data describing how the RadioButton was selected.</param>
        void Filter_Checked(object sender, RoutedEventArgs e)
        {
            // Mirror the change into the CollectionViewSource used by the corresponding ComboBox
            // to ensure that the change is reflected when snapped
            if (filtersViewSource.View != null)
            {
                var filter = (sender as FrameworkElement).DataContext;
                filtersViewSource.View.MoveCurrentTo(filter);
            }
        }

        private void OnItemClick(object sender, ItemClickEventArgs e)
        {
            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            var itemId = ((FWDataItem)e.ClickedItem).UniqueId;

            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            try
            {
                var x = FWDataSource.GetItem(itemId);
                if (x.Link.Contains("recensies"))
                    this.Frame.Navigate(typeof(ItemDetailPage), itemId);
                else
                    if (x.Link.Contains("/boeken"))
                        this.Frame.Navigate(typeof(ItemDetailPage), itemId);
                    else
                        if (x.Link.Contains("/auteurs"))
                            this.Frame.Navigate(typeof(AuthorDetailPage), itemId);
                        else
                            this.Frame.Navigate(typeof(RSSDetailPage), itemId);
            }
            catch
            {
            }
        }

        /// <summary>
        /// View model describing one of the filters available for viewing search results.
        /// </summary>
        private sealed class Filter : FantasyWereld.Common.BindableBase
        {
            private String _name;
            private int _count;
            private bool _active;

            public Filter(String name, int count, bool active = false)
            {
                this.Name = name;
                this.Count = count;
                this.Active = active;
            }

            public override String ToString()
            {
                return Description;
            }

            public String Name
            {
                get { return _name; }
                set { if (this.SetProperty(ref _name, value)) this.OnPropertyChanged("Description"); }
            }

            public int Count
            {
                get { return _count; }
                set { if (this.SetProperty(ref _count, value)) this.OnPropertyChanged("Description"); }
            }

            public bool Active
            {
                get { return _active; }
                set { this.SetProperty(ref _active, value); }
            }

            public String Description
            {
                get { return String.Format("{0} ({1})", _name, _count); }
            }
        }
        private void SearchBoxEventsSuggestionsRequested(object sender, SearchBoxSuggestionsRequestedEventArgs e)
        {
            string queryText = e.QueryText;
            if (!string.IsNullOrEmpty(queryText))
            {
                SearchSuggestionCollection suggestionCollection = e.Request.SearchSuggestionCollection;

                string[] terms = FWDataSource.AllKeywords;

                foreach (var term in terms)
                {
                    if (term.StartsWith(queryText, StringComparison.CurrentCultureIgnoreCase))
                        suggestionCollection.AppendQuerySuggestion(term);
                }
            }
        }

        /// <summary>
        /// Called when query submitted in SearchBox
        /// </summary>
        /// <param name="sender">The Xaml SearchBox</param>
        /// <param name="e">Event when user submits query</param>
        private void SearchBoxEventsQuerySubmitted(object sender, SearchBoxQuerySubmittedEventArgs e)
        {
            var queryText = e.QueryText;
            if (!string.IsNullOrEmpty(queryText))
            {
                // Load books if still necessary
                FWDataSource.LoadBooks();

                // If the Window isn't already using Frame navigation, insert our own Frame
                var previousContent = Window.Current.Content;
                var frame = previousContent as Frame;

                frame.Navigate(typeof(SearchResultsPage), queryText);
                Window.Current.Content = frame;

                // Google Analytics helper
                AnalyticsHelper.Setup();

                // Ensure the current window is active
                Window.Current.Activate();
            }
        }

        private void SearchBox_GotFocus(object sender, RoutedEventArgs e)
        {
            (sender as SearchBox).Width = 250;
        }

        private void SearchBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if ((sender as SearchBox).QueryText == "")
                (sender as SearchBox).Width = 35;
        }
    }
}
